package srclib;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
 * @author saad
 */
public class main extends javax.swing.JFrame {
    static Properties prop = new Properties();
    static String userHome = System.getProperty("user.home");
    private final  String addonAPPDir;
    private final String tunnelDIG;
    private final String tunnelUser;
    private final String tunnelKeyPPKPath;
    private final String tunnelLocalPort;
    private final String tunnelremoteAddress;
    private final String tunnelRemotePort;
    private final String tunnelPort;
    private final String tunnelAddress;
    private final String assignedRDPDirectPort;
    Process p = null;
    
    public main() {
        initComponents();
        addonAPPDir = prop.getProperty("addonAPPDir");
        tunnelDIG = prop.getProperty("tunnelDIG");
        tunnelUser = prop.getProperty("tunnelUser");
        tunnelKeyPPKPath = prop.getProperty("tunnelKeyPPKPath");
        tunnelLocalPort = prop.getProperty("tunnelLocalPort");
        tunnelremoteAddress = prop.getProperty("tunnelremoteAddress");
        tunnelRemotePort = prop.getProperty("tunnelRemotePort");
        tunnelPort = prop.getProperty("tunnelPort");
        tunnelAddress = prop.getProperty("tunnelAddress");
        assignedRDPDirectPort = prop.getProperty("assignedRDPDirectPort");
    }
    /**
     * This method is called from within the constructor to initialize the form.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel6 = new javax.swing.JLabel();
        connectInsecure = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        output = new javax.swing.JTextArea();
        pb = new javax.swing.JProgressBar();
        jLabel1 = new javax.swing.JLabel();
        connectSecure = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        systemExit = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Remote Desktop - Peterson Engineering Inc");
        setBackground(new java.awt.Color(34, 192, 245));
        setFocusTraversalPolicyProvider(true);
        setResizable(false);

        jLabel6.setFont(new java.awt.Font("NanumMyeongjo", 1, 36)); // NOI18N
        jLabel6.setText("Peterson Engineering Inc");
        jLabel6.setToolTipText("<html><center>\n<h2>Peterson Engineering Inc</h2><br />\n<h3>Remote Desktop RDP Ver 8.0</h3><br />\nSSH V2 Tunnel Forwarded RDP<br /><hr>\nClient Authentication using SSH PKI 2048 Bit<hr>\n</center></html>");

        connectInsecure.setText("RDP Direct (Not Secure)");
        connectInsecure.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        connectInsecure.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                connectInsecureActionPerformed(evt);
            }
        });

        output.setColumns(20);
        output.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
        output.setLineWrap(true);
        output.setRows(5);
        output.setBorder(javax.swing.BorderFactory.createTitledBorder("Output"));
        jScrollPane1.setViewportView(output);

        pb.setValue(0);
        pb.setStringPainted(true);

        jLabel1.setText("Secure RDP consists of you (the client) connecting to a tunnel provider (ssh server) such ");

        connectSecure.setText("Tunneled RDP (High Grade Security)");
        connectSecure.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        connectSecure.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                connectSecureActionPerformed(evt);
            }
        });

        jLabel2.setText("that your workstation RDP service is attached to your remote machine and then acessed");

        jMenu1.setText("File");

        systemExit.setText("Exit");
        systemExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                systemExitActionPerformed(evt);
            }
        });
        jMenu1.add(systemExit);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Control");

        jMenuItem1.setText("Properties");
        jMenu2.add(jMenuItem1);

        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(pb, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addComponent(jLabel6))
                        .addGap(0, 20, Short.MAX_VALUE))
                    .addComponent(connectInsecure, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(connectSecure, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1)
                .addGap(5, 5, 5)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(connectSecure, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(connectInsecure, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(pb, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void connectInsecureActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_connectInsecureActionPerformed
        new Thread(new insecureThreadRDPDirect()).start(); //Start the insecureThreadX1
    }//GEN-LAST:event_connectInsecureActionPerformed

    private void connectSecureActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_connectSecureActionPerformed
        //new Thread(new preRDPRoutine()).start(); //Start the preRDPRoutine
        output.append("Secure tunnel requested.\n");
        new Thread(new secureThreadSSH()).start(); //Start the insecureThreadX1
        output.append("launching RDP wrapped in SSH tunnel\n");
        new Thread(new tunneledThreadRDP()).start();
        output.append("Please wait...\n");
    }//GEN-LAST:event_connectSecureActionPerformed

    private void systemExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_systemExitActionPerformed
        new Thread(new processDestroyer()).start();
        System.exit(0);
    }//GEN-LAST:event_systemExitActionPerformed

    public class processDestroyer implements Runnable {
        @Override
        public void run(){
            try {
                try {
                    p = Runtime.getRuntime().exec("taskkill /F /IM plink.exe");
                } catch (IOException ex) {
                    Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
                }
                p.waitFor();
            } catch (InterruptedException ex) {
                Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    
    public class secureThreadSSH implements Runnable{
        
        @Override
        public void run(){
            try {
                try {
                    p = Runtime.getRuntime().exec("cmd.exe /c start /B " + addonAPPDir + tunnelDIG + " -l " + tunnelUser + " -i " + addonAPPDir + tunnelKeyPPKPath + " -v -L " + tunnelLocalPort + ":" + tunnelremoteAddress + ":" + tunnelRemotePort + " -P " + tunnelPort + " -2 -C -ssh " + tunnelAddress);
                    //output.append("process:"+ p);
                } catch (IOException ex) {
                    Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
                }
                p.waitFor();
            } catch (InterruptedException ex) {
                Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    
    public class tunneledThreadRDP implements Runnable {
        @Override
        public void run(){
            pb.setValue(0);            
        for (int i=0; i<=100; i++){ //Progressively increment variable i
                pb.setValue(i); //Set value
                pb.repaint(); //Refresh graphics
                try{Thread.sleep(100);} //Sleep 10 milliseconds
                catch (InterruptedException err){output.append(err + "\n");}
            }
            try {
                p = Runtime.getRuntime().exec("mstsc "+addonAPPDir+"connect.rdp");
                p.waitFor();
        } catch (IOException e1) {
            e1.printStackTrace();
            output.append(e1 + "\n");
        } catch (InterruptedException e1) {
            e1.printStackTrace();
            output.append(e1 + "\n");
        }
            pb.setValue(0);
            pb.repaint();
        throw new UnsupportedOperationException("Not supported yet.");
        }
    }
    public class secureThreadTestX1 implements Runnable{
        @Override
        public void run() {
            pb.setValue(0);
            for (int i=0; i<=100; i++){ //Progressively increment variable i
                pb.setValue(i); //Set value
                pb.repaint(); //Refresh graphics
                try{Thread.sleep(10);} //Sleep 10 milliseconds
                catch (InterruptedException err){output.append(err + "\n");}
            }
            try {
                p = Runtime.getRuntime().exec("cmd /C " + addonAPPDir+"");
                p.waitFor();
        } catch (IOException e1) {
            e1.printStackTrace();
            output.append(e1 + "\n");
        } catch (InterruptedException e1) {
            e1.printStackTrace();
            output.append(e1 + "\n");
        }
            pb.setValue(0);
            pb.repaint();
        throw new UnsupportedOperationException("Not supported yet.");
        }
}
    public class insecureThreadRDPDirect implements Runnable{
        @Override
        public void run(){
            pb.setValue(0);
            for (int i=0; i<=100; i++){ //Progressively increment variable i
                pb.setValue(i); //Set value
                pb.repaint(); //Refresh graphics
                try{Thread.sleep(10);} //Sleep 50 milliseconds
                catch (InterruptedException err){output.append(err + "\n");}
            }
            try {
                p = Runtime.getRuntime().exec("mstsc /v:petersoneng.us:"+assignedRDPDirectPort);
                p.waitFor();
        } catch (IOException e1) {
            e1.printStackTrace();
            output.append(e1 + "\n");
        } catch (InterruptedException e1) {
            e1.printStackTrace();
            output.append(e1 + "\n");
        }
            pb.setValue(0);
            pb.repaint();
        throw new UnsupportedOperationException("Not supported yet.");
        }
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            try (FileInputStream in = new FileInputStream(userHome + "/rdPEIproperties.xml")) {    
                prop.loadFromXML(in);
            } 
        } catch (IOException ex) {
        }
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new main().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton connectInsecure;
    private javax.swing.JButton connectSecure;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea output;
    private javax.swing.JProgressBar pb;
    private javax.swing.JMenuItem systemExit;
    // End of variables declaration//GEN-END:variables

}